#include <signal.h> 
#include <unistd.h> 
#include <bolt.h>
#include <prot.h>
#include "el.h"
#include "gw.h"

static void enable_cli(const char *prompt, const char *config)
{
  cli_init(prompt, config);
  struct el_events events = {
    .in_event = cli_in_event,
    .out_event = NULL
  };
  set_nonblock(STDIN_FILENO);
  el_add(STDIN_FILENO, &events, NULL);
}

static void disable_cli(void)
{
  cli_exit();
}

static void handle_signal(int num) 
{
   el_stop();
}

static void init_signal (void)
{
  signal (SIGHUP, handle_signal);
  signal (SIGINT, handle_signal);
  signal (SIGTERM, handle_signal);
  signal (SIGQUIT, handle_signal);
  signal (SIGSEGV, handle_signal);
  signal (SIGBUS, handle_signal);
  signal (SIGTSTP, handle_signal);
  signal (SIGTTIN, handle_signal);
  signal (SIGTTOU, handle_signal);
}


static void usage(const char *p)
{
  printf ("Usage:\n");
  printf ("  %s [-c <bp-file>] [-n <prompt>]\n", p);
  printf ("  %s -h\n", p);
}

int main(int argc, char *argv[])
{
  int ch;
  char name[128] = "trx";
  char config[128] = "trx.cmd";
  while((ch = getopt(argc, argv,"p:c:h"))!= -1) {
    switch(ch) {
    case 'c': snprintf(config, sizeof(config),"%s", optarg); break;
    case 'n': snprintf(name, sizeof(name),"%s", optarg); break;
    case 'h': /* fallthrough */
    default: usage(argv[0]);exit(0);
    }
  }
  el_init();
  init_signal();
  prot_init();
  gw_init();
  enable_cli(name, config);
  el_loop();
  disable_cli();
  gw_deinit();
  return 0;
}


